<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:29:32
 * @desc 微信支付配置
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Model;
use Wechat\Lib\Tools;
use app\comm\controller\PcLogController;
use app\comm\service\WeixinpayService;
class Zhifu extends PcLogController{
	/**
	 * 微信支付生成二维码图片
	 * @Author   lingyun
	 * @DateTime 2017-12-07T15:32:19+0800
	 * @return   [type]                   [description]
	 */
	public function create_paycode(){
		$post = input('param.');
		if(empty($post['order_sn'])){
			$this->error('缺少订单号',url('Index/index'));
		}
		$post["openid"] =$this->userinfo["openid"];
		$service = new WeixinpayService();		//实例化微信支付类
		$pay_code = $service->_pay_payqrc($post);	//支付二维码
		$result = json_decode($pay_code,true);
		if($result['code'] == 0){
			halt($result['msg']);
		}else{
			halt($result['url']);
		}
		// halt($result);
	}
	/**
	 * 微信支付
	 * @Author   lingyun
	 * @DateTime 2017-12-07T16:50:27+0800
	 * @return   [type]                   [description]
	 */
	public function weixin_pay(){
		$post = input('param.');
		$service = new WeixinpayService();		//实例化微信支付类
		$post["openid"] =$this->userinfo["openid"];
		$prepayid = $service->weixin_pay($post);

		//dd($prepayid);
		//var_dump($prepayid);
		

		if($prepayid !== false){
			$prepayid = json_encode($prepayid);
			$this->assign('data',$prepayid);
			return $this->fetch('weixinpay/weixin_pay');
		}else{
			$this->error('支付失败',url('Index/index'));
		}
	}
	/**
	 * 扫码支付回调地址
	 * @Author   lingyun
	 * @DateTime 2017-12-07T16:55:27+0800
	 * @return   [type]                   [description]
	 */
	public function notify(){
		$notifyInfo = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
        if (empty($notifyInfo)) {
            $this->error('支付失败',url('Index/index'));
        }
        if (empty($notifyInfo['sign'])) {
            $this->error('支付失败',url('Index/index'));
        }
        $data = $notifyInfo;
        unset($data['sign']);
        $partnerKey = sysconf('wechat_partnerkey');		//商户支付秘钥
        if ($notifyInfo['sign'] !== Tools::getPaySign($data, $partnerKey)) {
            $this->error('支付失败',url('Index/index'));
        }
        if($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
    		$order = Db::name('order')->where('order_sn',$notifyInfo['out_trade_no'])->field('id,uid,store_id,order_sn,pay_status,pay_time,pay_type')->find();
    		if($order['pay_status'] != 1){		//防止多次记录支付日志
    			$res = Db::name('order')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_status'=>1,'pay_time'=>time(),'pay_code'=>$notifyInfo['transaction_id'],'order_status'=>1]);		//更新支付状态
    			if($res !== false){
    				$res = Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>1,'amount'=>$notifyInfo['total_fee'],'addtime'=>time()]);
    				$res = Db::name('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>1,'pay_status'=>1,'status_desc'=>'订单已支付，待发货','store_id'=>$order['store_id'],'addtime'=>time()]);
    				$res>0?$this->success('支付成功',url('Index/index')):$this->error('支付失败',url('Index/index'));
    			}else{
    				$this->error('支付失败',url('Index/index'));
    			}
    		}else{
    			$this->success('支付成功',url('Index/index'));
    		}
        }
	}
	/**
	 * 向支付平台查询订单状态
	 * @Author   lingyun
	 * @DateTime 2017-12-08T15:02:42+0800
	 * @return   [type]                   [description]
	 */
	public function check_order($order_sn){
		$service = new WeixinpayService();		//实例化微信支付类
		halt($service->checkorderstatus($order_sn));
	}

	//微信支付
	public function weixinzhifu(){
		
		$script = &  load_wechat('Script');
		$url = $this->request->url(true);
		$config = $script->getJsSign($url,time());
		$config["debug"] = true;
		$this->assign('config',json_encode($config));
		$post = input('param.');
		$pay = & load_wechat('Pay');
		$openid=session("openid");
		$body  = "微信支付";
		$out_trade_no =time().rand(1000,900000);
		$total_fee   = 1;
		$notify_url= "http://ysbl.fxshe.com".url("@index/weixinpay/notify");
		$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
		$options = $pay->createMchPay($prepayid);
		//unset($options["timestamp"]);
		$this->assign('options',json_encode($options));
		return view("zhifu/weixinzhifu");
		//$qrc = $pay->getQrcPayUrl($post["order_sn"]);
	}



}